const { Controller } = require('egg');
const crypto = require('crypto');
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  async login(){
    this.ctx.validate({
      username: {
        type: "string",
        required: true,
        defValue: "",
        desc: "用户名称",
      },
      password: { type: "string", required: true, desc: "密码" },
    })
    console.log(this.updatepassword(this.ctx.request.body.password),"this.updatepassword(this.ctx.request.body.password)")
    const res=await this.app.model.Manager.findOne({
      where:{
        username:this.ctx.request.body.username,
        password:this.updatepassword(this.ctx.request.body.password)
      
      }
     })
    console.log(res,"res")
    if(!res){
      this.ctx.apiFail(res,"该用户不存在",400);
      return
    }
    let res1={}
    res1=JSON.parse(JSON.stringify(res));

    let token=await this.getToken(res1)
    if (!(await this.service.cache.set("user_" + res.id, token))) {
      this.ctx.throw(400, "登录失败")
  }
    res1.token=token
    
    this.ctx.apiSuccess(res1,"登录成功",200)
  }
  async userlogin(){
    this.ctx.validate({
      username: {
        type: "string",
        required: true,
        defValue: "",
        desc: "用户名称",
      },
      password: { type: "string", required: true, desc: "密码" },
    })
    console.log(this.updatepassword(this.ctx.request.body.password),"this.updatepassword(this.ctx.request.body.password)")
    const res=await this.app.model.User.findOne({
      where:{
        username:this.ctx.request.body.username,
        password:this.updatepassword(this.ctx.request.body.password)
      
      }
     })
    console.log(res,"res")
    if(!res){
      this.ctx.apiFail(res,"该用户不存在",400);
      return
    }
    let res1={}
    res1=JSON.parse(JSON.stringify(res));

    let token=await this.getToken(res1)
    if (!(await this.service.cache.set("user_" + res.id, token))) {
      this.ctx.throw(400, "登录失败")
  }
    res1.token=token
    
    this.ctx.apiSuccess(res1,"登录成功",200)
  }


  async getToken(value) {
    return this.app.jwt.sign(value, this.app.config.jwt.secret);
  }
  async checkpasseord(password, hashpassword) {
    const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
    hmac.update(password);
    password = hmac.digest("hex");

    return password === hashpassword;

  }
   updatepassword(password){
    const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
    hmac.update(password);
    password = hmac.digest("hex");
    return password
  }
}

module.exports = HomeController;
